import { Injectable } from '@angular/core';
import { BehaviorSubject, Subject, combineLatest, map } from 'rxjs';
import { Product } from './product';

const MOCK_PRODUCTS: Product[] = [
  {
    id: 1,
    imgUrl: '/assets/product-01.jpg',
    name: 'Organizer Set',
    color: 'Walnut',
    price: 149,
    description:
      'A good gift idea for housewarming, also used as storage tray or valet tray for keys and phones.',
  },
  {
    id: 2,
    imgUrl: '/assets/product-02.jpg',
    name: 'Leather Long Wallet',
    color: 'Natural',
    price: 75,
    description:
      'This great wallet is made of genuine leather and features multiple compartments for your credit cards, cash, and an ID window.',
  },
  {
    id: 3,
    imgUrl: '/assets/product-03.jpg',
    name: 'Machined Pencil and Pen Set',
    color: 'Black',
    price: 70,
    description:
      'Elegant writing pens that manage to strike a perfect balance between feeling substantial to hold, yet easy to write with for prolonged times.',
  },
  {
    id: 4,
    imgUrl: '/assets/product-04.jpg',
    name: 'Mini-Sketchbooks',
    color: 'Light Brown',
    price: 27,
    description:
      'Ideal for sketching, travel journal, doodling, taking notes, to-do list, brainstorming ideas, suitable for classroom, office, travel, etc. ',
  },
];

@Injectable({
  providedIn: 'root',
})
export class ProductService {
  // source
  private products = new BehaviorSubject<Product[]>(MOCK_PRODUCTS);
  selectedProductId = new BehaviorSubject<number>(0);

  // presentation
  products$ = this.products.asObservable();
  selectedProduct$ = combineLatest([
    this.products,
    this.selectedProductId,
  ]).pipe(map(([products, id]) => products.find((p) => p.id === id)));
}
